using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Collections;
using Microsoft.Win32;
using System.Net;
using Omniture.Studio.Objects;
using Omniture.API;
using System.Collections.ObjectModel;
using WeifenLuo.WinFormsUI.Docking;

namespace Omniture.Studio
{
	public partial class MDIForm : Form, IProgressPanel
	{
		#region Class Members
		
		private Options _options = new Options();
		private PropertiesWindow _propertyWindow = null;
		private ProjectForm _currentWizard = null;
		private MessageWindow _messageWindow = null;
		private ObjectsWindow _objectsWindow = null;		

		#endregion

		#region Constructors

		public MDIForm()
		{
			InitializeComponent();

			this.Size = new Size((int)(Screen.PrimaryScreen.WorkingArea.Width * 0.8), (int)(Screen.PrimaryScreen.WorkingArea.Height * 0.8));
			//this.Size = new Size(554, 439); //TEMP

			Globals.SetPanel(this);

			this.RefreshMenus();

			_propertyWindow = new PropertiesWindow();
			_propertyWindow.Show(dockPanel, DockState.DockLeft);
			_propertyWindow.RightToLeftLayout = RightToLeftLayout;			
			_propertyWindow.PropertyGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(propertyGrid1_PropertyValueChanged);

			_messageWindow = new MessageWindow();
			_messageWindow.Show(dockPanel, DockState.DockBottomAutoHide);

			_objectsWindow = new ObjectsWindow();
			_objectsWindow.Show(dockPanel, DockState.DockRight);

			menuProjectDocumentDesignExport.ToolTipText = "Generate the Site Design Reference to a file.";
			menuProjectDocumentTaggingExport.ToolTipText = "Generate the Site Tagging Schema to a file.";
			menuProjectDocumentDesignImport.ToolTipText = "Import the Site Design Reference from a file.";
			menuProjectDocumentTaggingImport.ToolTipText = "Import the Site Tagging Schema from a file.";

			menuProjectLoadASP.ToolTipText = "Load an ASP.NET project. This will load all web pages that are part of the specified project.";
			menuLoadWebsite.ToolTipText = "Load an ASP.NET website. This will load all web pages that are part of a specified folder tree.";
			menuProjectBuild.ToolTipText = "Build this project.";
			menuProjectPublishXML.ToolTipText = "Publishes the XML file for this project without recompiling binaries.";
			menuProjectVerify.ToolTipText = "Verify that this project is valid. This is done automatically before a build.";

			this.HelpButtonClicked += new CancelEventHandler(MDIForm_HelpButtonClicked);
			this.HelpRequested += new HelpEventHandler(MDIForm_HelpRequested);

			if (!Licensing.CheckLicense())
			{
				this.Text += " (Unlicensed)";
				MessageBox.Show("The license for this product has expired. Much of the functionality will not be available.", "License Info");
			}

		}

		private void MDIForm_HelpRequested(object sender, HelpEventArgs hlpevent)
		{
			
		}

		private void MDIForm_HelpButtonClicked(object sender, CancelEventArgs e)
		{
			
		}

		#endregion

		#region Property Implementations

		public OmnitureProject Project
		{
			get
			{
				if (this.CurrentWizard != null)
				{
					return this.CurrentWizard.Project;
				}
				return null;
			}
		}

		public ObjectsWindow ObjectsWindow
		{
			get { return _objectsWindow; }
		}

		public MessageWindow MessageWindow
		{
			get { return _messageWindow; }
		}

		public ProjectForm CurrentWizard
		{
			get { return _currentWizard; }
			set { _currentWizard = value; }
		}
		
		private string LogFileName
		{
			get { return System.IO.Path.Combine(Application.StartupPath, "BuildLog.txt"); }
		}
		
		#endregion

		#region Menu Handlers

		private void menuFileNew_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			OmnitureProject project = new OmnitureProject();
			project.ProjectName = "[New Project]";
			_objectsWindow.Project = project;
			ProjectForm F = new ProjectForm(this, project, _options);
			F.PropertiesForm = _propertyWindow.PropertyGrid;
			F.Refresh();

			//if (dockPanel.DocumentStyl == DocumentStyle.SystemMdi)
			//{
			//  F.MdiParent = this;
			//  F.Show();
			//}
			//else
			//{			
			F.Show(dockPanel);
			//}

			this.RefreshMenus();

		}
		
		private void menuFileOpen_Click(object sender, System.EventArgs e)
		{
			try
			{
				OpenFileDialog D = new OpenFileDialog();				
				D.DefaultExt = "oss";
				D.FileName = "*.oss";
				D.Title = "Open Project";
				D.Filter = "Omniture Site Studio Files (*.oss)|*.oss|All Files (*.*)|*.*";
				if(D.ShowDialog() == DialogResult.OK)
				{
					this.OpenFile(D.FileName);
				}

			}
			catch(Exception ex)
			{        
				throw;
			}
		}

		private void menuFileSave_Click(object sender, System.EventArgs e)
		{
			this.Save();			
		}

		private bool SaveAs()
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return false;

			try
			{
				SaveFileDialog D = new SaveFileDialog();
				D.DefaultExt = "oss";
				D.FileName = "*.oss";
				D.Title = "Save Project";
				D.Filter = "Omniture Site Studio Files (*.oss)|*.oss|All Files (*.*)|*.*";
				D.OverwritePrompt = true;
				D.CheckFileExists = false;

				if (File.Exists(this.Project.FileName))
				{
					FileInfo fi = new FileInfo(this.Project.FileName);
					D.InitialDirectory = fi.DirectoryName;
				}

				if (D.ShowDialog() == DialogResult.OK)
				{
					System.IO.FileInfo fi = new System.IO.FileInfo(D.FileName);
					if (fi.Exists && (fi.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
					{
						MessageBox.Show("The file is read-only. The operation has been aborted.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					else
					{						
						if (this.ActiveMdiChild is ProjectForm)
						{
							ProjectForm child = ((ProjectForm)this.ActiveMdiChild);
							child.Project.FileName = fi.FullName;
							child.Save();							
						}
						this.RefreshMenus();
						return true;
					}
				}

			}
			catch (Exception ex)
			{
				throw;
			}
			return false;
		}

		private void menuFileSaveAs_Click(object sender, System.EventArgs e)
		{
			this.SaveAs();
		}

		private void menuFileClose_Click(object sender, System.EventArgs e)
		{
			foreach (Form f in this.MdiChildren)
			{
				f.Close();
			}
			this.RefreshMenus();
		}

		private void menuFileExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void menuHelpAbout_Click(object sender, System.EventArgs e)
		{
			AboutForm F = new AboutForm();
			F.ShowDialog();
		}

		private void menuHelpLicensing_Click(object sender, System.EventArgs e)
		{
			LicenseForm F = new LicenseForm();
			F.ShowDialog();
		}

		private void menuHelpHelp_Click(object sender, System.EventArgs e)
		{
			FileInfo fi = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
			string fileName = Path.Combine(fi.DirectoryName, "GettingStarted.doc");
			if (System.IO.File.Exists(fileName))
			{
				System.Diagnostics.Process p = new System.Diagnostics.Process();
				p.StartInfo.FileName = fileName;
				p.StartInfo.CreateNoWindow = false;
				p.Start();
			}
			else
			{
				MessageBox.Show("There was an error opening the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void menuDGraphSettings_Click(object sender, System.EventArgs e)
		{
			//DGraphSettingsForm F = new DGraphSettingsForm();
			//F.Populate(this.DGraph);
			//if (F.ShowDialog() == DialogResult.OK)
			//{
			//  this.CurrentWizard.IsDirty = true;
			//}
		}

		private void menuProjectDocumentDesignImport_Click(object sender, System.EventArgs e)
		{
			//MessageBox.Show("Not Implemented", "Not Implemented", MessageBoxButtons.OK, MessageBoxIcon.Information);

			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			var d = new OpenFileDialog();
			d.Title = "Import Document Design Schema";
			d.Filter = "CSV File (*.csv)|*.csv";
			d.FilterIndex = 0;
			if (d.ShowDialog() != DialogResult.OK) return;

			string fileName = d.FileName;			
			string[] errorList = FileHelper.LoadDocumentDesign(this.Project, fileName);
			if (errorList.Length == 0)				
			{
				this.CurrentWizard.Refresh();
				this.CurrentWizard.IsDirty = true;
				MessageBox.Show("There load was successful.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{				
				//Errors
				this.MessageWindow.ErrorControl.ClearMessages();
				foreach (string s in errorList)
				{
					this.MessageWindow.ErrorControl.AddMessage(new Omniture.Studio.Objects.Message(MessageTypeConstants.Error, s));
				}
				MessageBox.Show("There were errors during this operation. Please see the message window for more details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void menuProjectDocumentTaggingImport_Click(object sender, System.EventArgs e)
		{
			//MessageBox.Show("Not Implemented", "Not Implemented", MessageBoxButtons.OK, MessageBoxIcon.Information);

			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			var d = new OpenFileDialog();
			d.Title = "Import Tagging Schema";
			d.Filter = "CSV File (*.csv)|*.csv";
			d.FilterIndex = 0;
			if (d.ShowDialog() != DialogResult.OK) return;

			string fileName = d.FileName;
			string[] errorList = FileHelper.LoadTaggingSchema(this.Project, fileName);
			if (errorList.Length == 0)
			{
				this.CurrentWizard.Refresh();
				this.CurrentWizard.IsDirty = true;
				MessageBox.Show("There load was successful.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{				
				this.MessageWindow.ErrorControl.ClearMessages();
				foreach (string s in errorList)
				{
					this.MessageWindow.ErrorControl.AddMessage(new Omniture.Studio.Objects.Message(MessageTypeConstants.Error, s));
				}
				MessageBox.Show("There were errors during this operation. Please see the message window for more details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		
		}

		private void menuProjectDocumentDesign_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			SaveFileDialog d = new SaveFileDialog();
			d.Title = "Save Solution Design Reference";
			d.Filter = "CSV File (*.csv)|*.csv";
			d.FilterIndex = 0;
			d.SupportMultiDottedExtensions = true;
			d.AddExtension = true;
			if (d.ShowDialog() != DialogResult.OK) return;

			string fileName = d.FileName;
			var sb = new StringBuilder();

			sb.AppendLine("Solution Design Reference - " + this.Project.ProjectName);
			sb.AppendLine("Last Updated: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
			sb.AppendLine();
			
			//Create the file text
			sb.AppendLine("EVAR LIST");
			sb.AppendLine("Variable,Alias,Description,Default,IsRequired");
			foreach (EVarItem item in this.Project.EVarList)
			{
				sb.AppendLine(item.Name + "," +
					item.Alias + "," +
					item.Description + "," + 
					item.DefaultValue + "," + 
					item.IsRequired);
			}
			sb.AppendLine();

			sb.AppendLine("PROP LIST");
			sb.AppendLine("Variable,Alias,Description,Default,IsRequired");
			foreach (PropItem item in this.Project.PropList)
			{
				sb.AppendLine(item.Name + "," + 
					item.Alias + "," +
					item.Description + "," + 
					item.DefaultValue + "," + 
					item.IsRequired);
			}
			sb.AppendLine();

			sb.AppendLine("EVENT LIST");
			sb.AppendLine("Variable,Alias,Description");
			foreach (EventItem item in this.Project.EventList)
			{
				sb.AppendLine(item.Name + "," +
					item.Alias + "," +
					item.Description);
			}
			sb.AppendLine();

			//Write the file
			StreamWriter sw =  File.CreateText(fileName);
			sw.Write(sb.ToString());
			sw.Close();

			if (System.IO.File.Exists(fileName))
			{
				System.Diagnostics.Process p = new System.Diagnostics.Process();
				p.StartInfo.FileName = fileName;
				p.StartInfo.CreateNoWindow = false;
				p.Start();
			}
			else
			{
				MessageBox.Show("There was an error opening the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void menuProjectDocumentTagging_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			SaveFileDialog d = new SaveFileDialog();
			d.Title = "Save Tagging Schema";
			d.Filter = "CSV File (*.csv)|*.csv";
			d.SupportMultiDottedExtensions = true;
			d.AddExtension = true;
			d.FilterIndex = 0;
			if (d.ShowDialog() != DialogResult.OK) return;

			string fileName = d.FileName;
			var sb = new StringBuilder();

			sb.AppendLine("Omniture Tagging Schema - " + this.Project.ProjectName);
			sb.AppendLine("Last Updated: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
			sb.AppendLine();
			
			//Create the file text
			sb.AppendLine("URL,Page Name,Channel,Events,Props,Evars");
			foreach (PageItem item in this.Project.PageList)
			{
				sb.Append(item.PageURL + "," + item.PageName + "," + item.ChannelName + ",");

				//Events
				string text = "";
				foreach (TrackReference reference in item.EventList)
				{
					text += reference.TrackItem.Name + ",";
				}
				if (text.EndsWith(",")) text = text.Substring(0, text.Length - 1);
				sb.Append("\"" + text + "\",");

				//Props
				text = "";
				foreach (TrackReference reference in item.PropList)
				{
					text += reference.TrackItem.Name + ",";
				}
				if (text.EndsWith(",")) text = text.Substring(0, text.Length - 1);
				sb.Append("\"" + text + "\",");

				//Evars
				text = "";
				foreach (TrackReference reference in item.EVarList)
				{
					text += reference.TrackItem.Name + ",";
				}
				if (text.EndsWith(",")) text = text.Substring(0, text.Length - 1);
				sb.AppendLine("\"" + text + "\"");

			}

			//Write the file
			StreamWriter sw = File.CreateText(fileName);
			sw.Write(sb.ToString());
			sw.Close();

			if (System.IO.File.Exists(fileName))
			{
				System.Diagnostics.Process p = new System.Diagnostics.Process();
				p.StartInfo.FileName = fileName;
				p.StartInfo.CreateNoWindow = false;
				p.Start();
			}
			else
			{
				MessageBox.Show("There was an error opening the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void menuProjectLoadASP_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			OpenFileDialog d = new OpenFileDialog();
			d.Title = "Choose .NET Project";
			d.Filter = ".NET Project Files (*.csproj)|*.csproj|All Files (*.*)|*.*";
			d.FilterIndex = 0;
			if (d.ShowDialog() == DialogResult.OK)
			{
				XmlDocument document = new XmlDocument();
				document.Load(d.FileName);				

				//XPath does not work, so do it the hard way
				var pageList = new List<string>();
				foreach (XmlNode node in document.DocumentElement.ChildNodes)
				{
					if (node.Name == "ItemGroup")
					{
						foreach (XmlNode child in node.ChildNodes)
						{
							if (child.Name == "Content")
							{
								string v = child.Attributes["Include"].Value;
								if (v.ToLower().EndsWith(".aspx"))
								{
									pageList.Add(v.Replace(@"\","/"));
								}
							}
						}
					}
				}

				var skippedList = new List<string>();
				var addedList = new List<PageItem>();

				//Now load into the collection
				foreach (string pageName in pageList)
				{
					var page = new PageItem(this.Project);
					page.PageURL = "/" + pageName;
					string[] arr = pageName.Split('/');
					page.PageName = arr[arr.Length - 1].Substring(0, arr[arr.Length - 1].Length - 5);
					page.ChannelName = page.PageName;

					if (this.Project.PageList.GetByUrl(page.PageURL) == null)
						addedList.Add(page);
					else
						skippedList.Add(pageName);
				}

				//Prompt the user
				if (MessageBox.Show("There are " + addedList.Count + " items to be imported and " + skippedList.Count + " skipped. Do you wish to continue?", "Import?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					this.Project.PageList.AddRange(addedList);
					this.CurrentWizard.IsDirty = true;
					this.CurrentWizard.ReloadPages();
					this.CurrentWizard.UpdateDisplay();
					MessageBox.Show("The .NET project was imported successfully. A total of " + addedList.Count + " pages were added.", ".NET Project Imported", MessageBoxButtons.OK, MessageBoxIcon.Information);
				}

			}
		}

		private void menuLoadWebsite_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			var F = new FolderBrowserDialog();
			F.Description = "Choose the site folder to import";
			if (F.ShowDialog() == DialogResult.OK)
			{
				List<string> pageList = new List<string>();
				string[] files = Directory.GetFiles(F.SelectedPath, "*.aspx", SearchOption.AllDirectories);
				foreach (string file in files)
				{
					string f = file.Substring(F.SelectedPath.Length, file.Length - F.SelectedPath.Length);
					pageList.Add(f.Replace(@"\", "/"));
				}

				var skippedList = new List<string>();
				var addedList = new List<PageItem>();

				//Now load into the collection
				foreach (string pageName in pageList)
				{
					var page = new PageItem(this.Project);
					page.PageURL = pageName;
					string[] arr = pageName.Split('/');
					page.PageName = arr[arr.Length - 1].Substring(0, arr[arr.Length - 1].Length - 5);
					page.ChannelName = page.PageName;

					if (this.Project.PageList.GetByUrl(page.PageURL) == null)
						addedList.Add(page);
					else
						skippedList.Add(pageName);
				}

				//Prompt the user
				if (MessageBox.Show("There are " + addedList.Count + " items to be imported and " + skippedList.Count + " skipped. Do you wish to continue?", "Import?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					this.Project.PageList.AddRange(addedList);
					this.CurrentWizard.IsDirty = true;
					this.CurrentWizard.ReloadPages();
					this.CurrentWizard.UpdateDisplay();
				}

				MessageBox.Show("The .NET project was imported successfully. A total of " + addedList.Count + " pages were added.", ".NET Project Imported", MessageBoxButtons.OK, MessageBoxIcon.Information);

			}
		}

		private void menuProjectBuild_Click(object sender, System.EventArgs e)
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return;

			if (this.CurrentWizard != null)
			{
				this.CurrentWizard.BuildProject();
				
				BuildSummaryForm F = new BuildSummaryForm();
				F.SummaryText = "Custom library compiled and copied it to the following location:\r\n" +
				Path.Combine(this.Project.LibraryFilePath, this.Project.LibraryName) + "\r\n\r\n" +
				"XML configuration file generated and copied to the following location:\r\n" +
				Path.Combine(this.Project.ConfigFilePath, this.Project.XMLConfigFileName);
				F.ShowDialog();
			}
		}

		private void menuProjectPublishXML_Click(object sender, System.EventArgs e)
		{
			if (this.CurrentWizard != null)
			{
				this.CurrentWizard.PublishXML();

				BuildSummaryForm F = new BuildSummaryForm();
				F.SummaryText = "XML configuration file generated and copied to the following location:\r\n" +
				Path.Combine(this.Project.ConfigFilePath, this.Project.XMLConfigFileName);
				F.ShowDialog();

			}
		}

		private void menuProjectVerify_Click(object sender, System.EventArgs e)
		{
			if (this.CurrentWizard != null)
			{
				try
				{
					this.CurrentWizard.LockUI();
					this.MessageWindow.ErrorControl.ClearMessages();

					//Errors
					ReadOnlyCollection<string> errorList = this.CurrentWizard.Project.GetErrorList();
					foreach (string s in errorList)
					{
						this.MessageWindow.ErrorControl.AddMessage(new Omniture.Studio.Objects.Message(MessageTypeConstants.Error, s));
					}

					//Warnings
					ReadOnlyCollection<string> warningList = this.CurrentWizard.Project.GetWarningList();
					foreach (string s in warningList)
					{
						this.MessageWindow.ErrorControl.AddMessage(new Omniture.Studio.Objects.Message(MessageTypeConstants.Warning, s));
					}

					if ((errorList.Count + warningList.Count) == 0)
					{
						MessageBox.Show("The project is valid.", "Validated", MessageBoxButtons.OK, MessageBoxIcon.Information);
					}
					else
					{
						MessageBox.Show("The project is has warnings or errors valid. Please check the messages window.", "Not Valid!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					}

				}
				catch (Exception ex)
				{
					throw;
				}
				finally
				{
					this.CurrentWizard.UnlockUI();
				}
			}
		}

		private void menuToolsOptions_Click(object sender, System.EventArgs e)
		{
			//OptionsForm F = new OptionsForm();
			//F.Options = _options;

			//if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
			//{
			//  F.MdiParent = this;
			//  F.Show();
			//}
			//else
			//{
			//  F.Show(dockPanel);
			//}
		}

		private void menuToolViewLog_Click(object sender, System.EventArgs e)
		{
			if (System.IO.File.Exists(this.LogFileName))
			{
				System.Diagnostics.Process p = new System.Diagnostics.Process();
				p.StartInfo.FileName = "notepad.exe";
				p.StartInfo.Arguments = this.LogFileName;
				p.StartInfo.CreateNoWindow = false;
				p.Start();
			}
			else
			{
				MessageBox.Show("There is no log file.", "No Log", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}

		#endregion

		#region Methods

		public bool Save()
		{
			//This feature requires licensing
			if (!Licensing.CheckLicense()) return false;

			try
			{
				if (this.Project != null)
				{
					if (this.Project.FileName != "")
					{
						System.IO.FileInfo fi = new System.IO.FileInfo(this.Project.FileName);
						if (fi.Exists && (fi.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
						{
							return this.SaveAs();
						}
						else
						{
							//this.DGraph.Save(this.DGraph.FileName);
							if (this.ActiveMdiChild is ProjectForm)
							{
								ProjectForm child = ((ProjectForm)this.ActiveMdiChild);
								child.Save();
								return true;
							}
						}

					}
					else
					{
						return this.SaveAs();
					}
				}

			}
			catch (Exception ex)
			{
				throw;
			}
			return false;

		}

		public OmnitureProject OpenFile(string fileName)
		{
			//Ensure the file exists
			if (!File.Exists(fileName))
			{
				MessageBox.Show("The specified file does not exist!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);				
				return null;
			}

			string unlockKey = Globals.ShowProgress("Loading Project...");
			try
			{
				OmnitureProject project = new OmnitureProject();
				project.Load(fileName);
				_objectsWindow.Project = project;
				ProjectForm F = new ProjectForm(this, project, _options);
				F.PropertiesForm = _propertyWindow.PropertyGrid;
				F.Refresh();

				//if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
				//{
				//  F.MdiParent = this;
				//  F.Show();
				//}
				//else
				//{
					F.Show(dockPanel);
				//}

				this.RefreshMenus();
				return project;

			}
			catch (Exception ex)
			{
				throw;
			}
			finally
			{
				Globals.HideProgress(unlockKey);
			}
		}

		public void UpdateCaption(ProjectForm wizard)
		{
			foreach (IDockContent content in dockPanel.Contents)
			{
				if (content.DockHandler.Form == wizard)
				{
					content.DockHandler.TabText = wizard.Text;
				}
			}
		}

		public void EnableMenus(bool value)
		{
			foreach (ToolStripItem tsi in this.menuStrip1.Items)
			{
				tsi.Enabled = value;
			}
		}

		private void RefreshMenus()
		{
			try
			{
				bool isOpen = (this.Project != null);
				bool isProcessing = ((IProgressPanel)this).IsProcessing;
				bool isLicensed = Licensing.CheckLicense();

				menuFileClose.Enabled = isOpen && !isProcessing;
				menuFileNew.Enabled = !isProcessing && isLicensed;
				menuFileOpen.Enabled = !isProcessing;
				menuFileSave.Enabled = isOpen && !isProcessing && isLicensed;
				menuFileSaveAs.Enabled = isOpen && !isProcessing && isLicensed;
				menuFileExit.Enabled = !isProcessing;

				menuProjectBuild.Enabled = isOpen && isLicensed;
				menuProjectPublishXML.Enabled = isOpen && isLicensed;
				menuProjectVerify.Enabled = isOpen;
				menuProjectLoadASP.Enabled = isOpen && isLicensed;
				menuLoadWebsite.Enabled = isOpen && isLicensed;
				menuProjectDocumentDesignExport.Enabled = isOpen && isLicensed;
				menuProjectDocumentTaggingExport.Enabled = isOpen && isLicensed;
				menuProjectDocumentDesignImport.Enabled = isOpen && isLicensed;
				menuProjectDocumentTaggingImport.Enabled = isOpen && isLicensed;

			}
			catch(Exception ex)
			{        
				throw;
			}
		}

		private void SetStatus()
		{
			this.SetStatus("");
		}

		private void SetStatus(string text)
		{
			if(text == "")
				pnlStatus.Text = "Ready!";
			else
				pnlStatus.Text = text;
		}

		#endregion

		#region Event Handlers

		private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
		{			
			try
			{
				if (e.OldValue.ToString() != e.ChangedItem.Value.ToString())
				{					
					object[] list = _propertyWindow.PropertyGrid.SelectedObjects;
					if (list[0] is ITrackItem)
					{
						//If chaning the name/alias then check the code name for uniqueness
						if ((e.ChangedItem.Label == "Name") || (e.ChangedItem.Label == "Alias"))
						{
							int count = this.CurrentWizard.Project.GetList(((ITrackItem)list[0]).ItemType).Count(x => x.CodeName == e.ChangedItem.Value.ToString());
							if (count > 1)
							{
								MessageBox.Show("The specified value conflicts with another object.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
								foreach (object o in list)
								{
									e.ChangedItem.PropertyDescriptor.SetValue(o, e.OldValue);
								}
								_propertyWindow.PropertyGrid.Refresh();
								return;
							}
						}
					}
					else if (list[0] is PageItem)
					{
						//If chaning the name/alias then check the code name for uniqueness
						if (e.ChangedItem.Label == "PageURL")
						{
							int count = this.CurrentWizard.Project.PageList.Count(x => x.PageURL == e.ChangedItem.Value.ToString());
							if (count > 1)
							{
								MessageBox.Show("The specified value conflicts with another object.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
								foreach (object o in list)
								{
									e.ChangedItem.PropertyDescriptor.SetValue(o, e.OldValue);
								}
								_propertyWindow.PropertyGrid.Refresh();
								return;
							}
						}
					}

					this.CurrentWizard.IsDirty = true;
					this.CurrentWizard.UpdateDisplay();
					_propertyWindow.PropertyGrid.SelectedObjects = list;
				}
				this.ObjectsWindow.UpdateDisplay();
			}
			catch (Exception ex)
			{
				//Fallback is make dirty
				this.CurrentWizard.IsDirty = true;
			}
		}
		
		private void timer1_Tick(object sender, System.EventArgs e)
		{			
			pnlTime.Text = DateTime.Now.ToShortTimeString();
		}

		private void timer2_Tick(object sender, System.EventArgs e)
		{
			TimeSpan ts = DateTime.Now.Subtract(startTimer);
			pnlDuration.Text = ts.Hours.ToString("00") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00");
			this.Refresh();
		}

		private void MDIForm_MdiChildActivate(object sender, System.EventArgs e)
		{
			this.RefreshMenus();
		}

		private void dockPanel_ActiveDocumentChanged(object sender, System.EventArgs e)
		{			
			try
			{
				if (_propertyWindow != null)
				{
					if (_propertyWindow.PropertyGrid != null)
					{
						_propertyWindow.PropertyGrid.SelectedObject = null;
					}
				}
			}
			catch (Exception ex)
			{
				//Do Nothing = This happens on app close
			}

			if (((DockPanel)sender).ActiveContent is ProjectForm)
			{
				this.CurrentWizard = (ProjectForm)((DockPanel)sender).ActiveContent;
				((DockPanel)sender).ActiveContent.DockHandler.TabText = this.CurrentWizard.Text;
			}
			else
			{
				this.CurrentWizard = null;
			}
			this.RefreshMenus();
		}

		#endregion

		#region IProgressPanel Members

		private List<string> _unlockKeyList = new List<string>();
		private DateTime startTimer;
		string IProgressPanel.ProcessStart(string text)
		{
			startTimer = DateTime.Now;
			timer2.Enabled = true;
			timer2.Start();
			pnlStatus.Text = text;
			System.Windows.Forms.Application.DoEvents();
			string key = Guid.NewGuid().ToString();
			_unlockKeyList.Add(key);
			this.RefreshMenus();
			return key;

		}

		void IProgressPanel.ProcessComplete(string unlockKey)
		{
			if (_unlockKeyList.Contains(unlockKey))
			{
				_unlockKeyList.Remove(unlockKey);
			}

			if (!((IProgressPanel)this).IsProcessing)
			{
				timer2.Enabled = false;
				pnlDuration.Text = "";
				pnlStatus.Text = "Ready!";
				this.RefreshMenus();
			}
		}

		bool IProgressPanel.IsProcessing
		{
			get { return (_unlockKeyList.Count > 0); }
		}

		#endregion

	}

}